<!-- 用户编辑弹窗 -->
<template>
  <RadModal
    width="80%"
    :visible="visible"
    :loading="loading"
    title="用户"
    @visible-change="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
    >
      <a-row :gutter="0">
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="用户名" name="userName">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入用户名"
              v-model:value="form.userName"
            />
          </a-form-item>
        </a-col>
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="昵称" name="nickName">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入昵称"
              v-model:value="form.nickName"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="0">
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="真实姓名" name="realName">
            <a-input
              allow-clear
              :maxlength="100"
              placeholder="请输入真实姓名"
              v-model:value="form.realName"
            />
          </a-form-item>
        </a-col>
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="出生日期">
            <a-date-picker
              class="ele-fluid"
              value-format="YYYY-MM-DD"
              placeholder="请选择出生日期"
              v-model:value="form.birthday"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="0">
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="性别">
            <a-radio-group
              size="default"
              v-model:value="form.sex"
              button-style="solid"
            >
              <a-radio-button :value="1">男</a-radio-button>
              <a-radio-button :value="2">女</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="手机号" name="phone">
            <a-input
              allow-clear
              :maxlength="11"
              placeholder="请输入手机号"
              v-model:value="form.phone"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="0">
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="邮箱" name="email">
            <a-input
              allow-clear
              :maxlength="100"
              placeholder="请输入邮箱"
              v-model:value="form.email"
            />
          </a-form-item>
        </a-col>
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="证件号码">
            <a-input
              allow-clear
              :maxlength="100"
              placeholder="请输入证件号码"
              v-model:value="form.idCard"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col v-bind="{ span: 24 }">
          <a-form-item :label-col="{ md: 2 }" label="个性签名">
            <a-input
              allow-clear
              placeholder="请输入个性签名"
              v-model:value="form.signature"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col v-bind="{ span: 24 }">
          <a-form-item :label-col="{ md: 2 }" label="个人简介">
            <a-input
              allow-clear
              placeholder="请输入个人简介"
              v-model:value="form.introduction"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="0">
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="所属机构" name="orgId">
            <a-tree-select
              allow-clear
              tree-default-expand-all
              placeholder="请选择上级机构"
              v-model:value="form.orgId"
              :fieldNames="{ label: 'name', value: 'id' }"
              :tree-data="orglist"
              :dropdown-style="{ maxHeight: '360px', overflow: 'auto' }"
            />
          </a-form-item>
        </a-col>
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="职位">
            <a-select
              v-model:value="form.posId"
              :options="poslist"
              :field-names="{ label: 'name', value: 'id' }"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="0">
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="工号">
            <a-input
              allow-clear
              placeholder="请输入工号"
              v-model:value="form.jobNum"
            />
          </a-form-item>
        </a-col>
        <a-col v-bind="{ span: 12 }">
          <a-form-item label="岗位状态">
            <a-select v-model:value="form.jobStatus">
              <a-select-option :value="1">在职</a-select-option>
              <a-select-option :value="2">离职</a-select-option>
              <a-select-option :value="3">请假</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="2">
        <a-col v-bind="{ span: 24 }">
          <a-form-item :label-col="{ md: 2 }" label="备注">
            <a-textarea
              :rows="4"
              :maxlength="200"
              placeholder="请输入备注"
              v-model:value="form.remark"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </RadModal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, onMounted } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { emailReg, phoneReg } from 'ele-admin-pro/es';
  import useFormData from '@/utils/use-form-data';
  import RadModal from '@/components/RadModal/index.vue';
  import { addUser, updateUser } from '@/api/system/user';
  import { listOrganizations } from '@/api/system/organization';
  import { list as PosList } from '@/api/system/pos';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import type { User } from '@/api/system/user/model';
  import { Organization } from '@/api/system/organization/model';
  import { Position } from '@/api/system/pos/model';

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: User | null;
  }>();

  //
  const formRef = ref<FormInstance | null>(null);

  const orglist = ref<Organization[]>([]);
  const poslist = ref<Position[] | undefined>([]);

  // 是否是修改
  const isUpdate = ref(false);

  // 提交状态
  const loading = ref(false);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<User>({
    id: undefined,
    userName: '',
    nickName: '',
    realName: '',
    avatar: '',
    sex: 1,
    roles: [],
    signature: '',
    orgId: undefined,
    posId: undefined,
    jobNum: '',
    jobStatus: 1,
    email: '',
    phone: '',
    password: '',
    introduction: '',
    birthday: '',
    remark: ''
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    userName: [
      {
        required: true,
        type: 'string',
        trigger: 'blur'
      }
    ],
    nickName: [
      {
        required: true,
        message: '请输入用户名',
        type: 'string',
        trigger: 'blur'
      }
    ],
    realName: [
      {
        required: true,
        message: '请输入用户名',
        type: 'string',
        trigger: 'blur'
      }
    ],
    orgId: [
      {
        required: true,
        message: '请选择所属机构',
        type: 'number',
        trigger: 'blur'
      }
    ],
    roles: [
      {
        required: true,
        message: '请选择角色',
        type: 'array',
        trigger: 'blur'
      }
    ],
    email: [
      {
        pattern: emailReg,
        message: '邮箱格式不正确',
        type: 'string',
        trigger: 'blur'
      }
    ],
    password: [
      {
        required: true,
        type: 'string',
        validator: async (_rule: Rule, value: string) => {
          if (isUpdate.value || /^[\S]{5,18}$/.test(value)) {
            return Promise.resolve();
          }
          return Promise.reject('密码必须为5-18位非空白字符');
        },
        trigger: 'blur'
      }
    ],
    phone: [
      {
        required: true,
        pattern: phoneReg,
        message: '手机号格式不正确',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const saveOrUpdate = isUpdate.value ? updateUser : addUser;
        saveOrUpdate(form)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };
  onMounted(async () => {
    orglist.value = await listOrganizations();
    poslist.value = await PosList();
  });
  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields({
            ...props.data,
            password: ''
          });
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
